<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>密钥配置 - 密钥管理服务</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- 共享响应式样式 -->
    <link href="shared_responsive.css" rel="stylesheet">
    <!-- 通用工具函数 -->
    <script src="../common/common.js"></script>
    <style>
        article {
            background-color: #f8fafc;
            background-image: radial-gradient(rgba(59, 130, 246, 0.05) 1px, transparent 1px);
            background-size: 20px 20px;
            background-position: 0 0, 10px 10px;
            color: #334155;
            min-height: 100vh;
        }
        
        /* 卡片样式 */
        .card {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(59, 130, 246, 0.4);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.02);
            transition: all 0.3s ease;
            backdrop-filter: blur(20px);
        }
        
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
        }
        
        /* 按钮样式 */
        .btn {
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background-color: rgba(59, 130, 246, 0.1);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }
        
        .btn:hover::before {
            width: 300px;
            height: 300px;
        }
        
        .btn-primary {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.3);
        }
        
        .btn-primary:hover {
            background-color: rgba(59, 130, 246, 0.25);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
        }
        
        /* 输入框样式 */
        .input-field {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(59, 130, 246, 0.3);
            border-radius: 8px;
            transition: all 0.3s ease;
        }
        
        .input-field:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            transform: translateY(-1px);
        }
        
        /* 标签页样式 */
        .tab-btn {
            transition: all 0.3s ease;
            border-bottom: 2px solid transparent;
            position: relative;
        }
        
        .tab-btn.active {
            border-bottom-color: #3b82f6;
            color: #3b82f6;
            background-color: rgba(59, 130, 246, 0.05);
        }
        
        .tab-btn:hover:not(.active) {
            color: #3b82f6;
            background-color: rgba(59, 130, 246, 0.02);
        }
        
        /* 算法和密钥类型徽章 */
        .algorithm-badge,
        .key-type-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .algorithm-sm2 {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
        }
        
        .algorithm-rsa {
            background-color: rgba(34, 197, 94, 0.15);
            color: #16a34a;
        }
        
        .algorithm-sm4 {
            background-color: rgba(234, 179, 8, 0.15);
            color: #d97706;
        }
        
        .algorithm-aes {
            background-color: rgba(239, 68, 68, 0.15);
            color: #dc2626;
        }
        
        .key-type-main {
            background-color: rgba(139, 92, 246, 0.15);
            color: #8b5cf6;
        }
        
        .key-type-kek {
            background-color: rgba(236, 72, 153, 0.15);
            color: #ec4899;
        }
        
        .key-type-dek {
            background-color: rgba(14, 165, 233, 0.15);
            color: #0ea5e9;
        }
        
        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            backdrop-filter: blur(5px);
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .modal-overlay.show {
            opacity: 1;
        }
        
        .modal-content {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            padding: 2rem;
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            transform: translateY(20px);
            transition: transform 0.3s ease;
            backdrop-filter: blur(20px);
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
        }
        
        .modal-overlay.show .modal-content {
            transform: translateY(0);
        }
        
        /* 自定义滚动条 */
        ::-webkit-scrollbar {
            width: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: rgba(59, 130, 246, 0.1);
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: rgba(59, 130, 246, 0.4);
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: rgba(59, 130, 246, 0.6);
        }
        
        /* 标题样式 */
        h1 {
            font-size: clamp(1.5rem, 3vw, 2rem);
            font-weight: bold;
            color: #334155;
            animation: fadeInDown 0.5s ease-out;
        }
        
        /* 确保100%宽度布局 */
        section {
            width: 100%;
            max-width: 100%;
        }
        
        /* 表格样式增强 */
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 0.75rem;
            text-align: left;
            border-bottom: 1px solid rgba(99, 116, 139, 0.2);
            transition: all 0.3s ease;
        }
        
        th {
            background-color: rgba(241, 245, 249, 0.8);
            font-weight: 600;
            color: #475569;
        }
        
        tr:hover td {
            background-color: rgba(59, 130, 246, 0.02);
        }
        
        /* 激活状态指示 */
        .active-indicator {
            position: relative;
        }
        
        .active-indicator::before {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            width: 3px;
            height: 100%;
            background-color: #3b82f6;
            border-radius: 0 3px 3px 0;
        }
        
        /* 脉冲效果 */
        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(59, 130, 246, 0.4);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(59, 130, 246, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(59, 130, 246, 0);
            }
        }
        
        .pulse {
            animation: pulse 2s infinite;
        }
        
        /* 悬浮动画 */
        @keyframes float {
            0% {
                transform: translateY(0px);
            }
            50% {
                transform: translateY(-4px);
            }
            100% {
                transform: translateY(0px);
            }
        }
        
        .float {
            animation: float 3s ease-in-out infinite;
        }
        
        /* Toast 提示增强 */
        #toast-container .toast {
            transition: all 0.3s ease;
            transform: translateX(100%);
        }
        
        #toast-container .toast.show {
            transform: translateX(0);
            animation: slideInRight 0.3s ease-out;
        }
        
        /* 动画定义 */
        @keyframes fadeInDown {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        @keyframes slideInRight {
            from {
                opacity: 0;
                transform: translateX(100%);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }
        
        /* 返回按钮样式 */
        .back-btn {
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }
        
        .back-btn::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 0;
            height: 0;
            border-radius: 50%;
            background-color: rgba(255, 255, 255, 0.3);
            transform: translate(-50%, -50%);
            transition: width 0.6s, height 0.6s;
        }
        
        .back-btn:hover::before {
            width: 300px;
            height: 300px;
        }
        
        .back-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
        }
    </style>
</head>
<body>
    <!-- 背景网格层 -->
    <article>
    <!-- 主要内容层 -->
    <section id="main-content" class="p-6">
        <!-- Toast 容器 -->
        <div id="toast-container" class="fixed top-4 right-4 z-50"></div>
        
        <!-- 页面标题区 -->
        <header class="mb-6 pb-4 border-b border-[rgba(99,116,139,0.2)]">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h1 class="clamp(1.5rem,3vw,2rem) font-bold text-[#334155]">密钥配置</h1>
                    <p class="text-[#64748b] text-sm mt-1">管理应用主密钥、KEK和DEK密钥配置</p>
                </div>
                <a href="index.html" class="back-btn bg-blue-500 text-white px-4 py-2 rounded-lg inline-flex items-center gap-2 hover:shadow-md">
                    <i class="fas fa-arrow-left"></i>
                    <span>返回主页</span>
                </a>
            </div>
        </header>
        
        <!-- 主内容区 -->
        <main>
            <!-- 选项卡 -->
            <div class="mb-6 flex flex-wrap border-b border-[rgba(99,116,139,0.2)]">
                <button class="tab-btn px-6 py-3 font-medium text-sm transition-all duration-300 active" data-tab="main-keys">
                    <i class="fas fa-key mr-2"></i>应用主密钥
                </button>
                <button class="tab-btn px-6 py-3 font-medium text-sm transition-all duration-300" data-tab="kek-keys">
                    <i class="fas fa-lock mr-2"></i>KEK管理
                </button>
                <button class="tab-btn px-6 py-3 font-medium text-sm transition-all duration-300" data-tab="dek-keys">
                    <i class="fas fa-shield-alt mr-2"></i>DEK管理
                </button>
            </div>
            
            <!-- 应用主密钥 -->
            <div id="main-keys" class="tab-content">
                <div class="card p-6 mb-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-lg font-semibold">应用主密钥列表</h2>
                        <button class="btn btn-primary px-4 py-2 rounded-lg inline-flex items-center gap-2 hover:shadow-md" onclick="openAddKeyModal('main')">
                            <i class="fas fa-plus"></i>
                            <span>新建主密钥</span>
                        </button>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="border-b border-[rgba(99,116,139,0.2)]">
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">密钥ID</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">密钥名称</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">算法类型</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">创建时间</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">状态</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">操作</th>
                                </tr>
                            </thead>
                            <tbody id="mainKeysTable">
                                <!-- 数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- KEK管理 -->
            <div id="kek-keys" class="tab-content hidden">
                <div class="card p-6 mb-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-lg font-semibold">KEK密钥列表</h2>
                        <button class="btn btn-primary px-4 py-2 rounded-lg inline-flex items-center gap-2 hover:shadow-md" onclick="openAddKeyModal('kek')">
                            <i class="fas fa-plus"></i>
                            <span>新建KEK</span>
                        </button>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="border-b border-[rgba(99,116,139,0.2)]">
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">密钥ID</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">密钥名称</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">算法类型</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">创建时间</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">状态</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">操作</th>
                                </tr>
                            </thead>
                            <tbody id="kekKeysTable">
                                <!-- 数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- DEK管理 -->
            <div id="dek-keys" class="tab-content hidden">
                <div class="card p-6 mb-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-lg font-semibold">DEK密钥列表</h2>
                        <button class="btn btn-primary px-4 py-2 rounded-lg inline-flex items-center gap-2 hover:shadow-md" onclick="openAddKeyModal('dek')">
                            <i class="fas fa-plus"></i>
                            <span>新建DEK</span>
                        </button>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="border-b border-[rgba(99,116,139,0.2)]">
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">密钥ID</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">密钥名称</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">算法类型</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">保护密钥</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">创建时间</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">状态</th>
                                    <th class="text-left py-3 px-4 font-semibold text-sm text-[#64748b]">操作</th>
                                </tr>
                            </thead>
                            <tbody id="dekKeysTable">
                                <!-- 数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </section>
    </article>
    
    <!-- 新建密钥模态框 -->
    <div id="addKeyModal" class="modal-overlay hidden">
        <div class="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold" id="modalTitle">新建密钥</h3>
                <button onclick="closeModal('addKeyModal')" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <form id="addKeyForm">
                <input type="hidden" id="keyType" name="keyType">
                <div class="space-y-4">
                    <div>
                        <label for="keyName" class="block text-sm font-medium text-gray-700 mb-1">密钥名称</label>
                        <input type="text" id="keyName" name="keyName" class="input-field w-full px-4 py-2" required>
                    </div>
                    <div>
                        <label for="algorithm" class="block text-sm font-medium text-gray-700 mb-1">算法类型</label>
                        <select id="algorithm" name="algorithm" class="input-field w-full px-4 py-2" required>
                            <option value="">请选择算法</option>
                            <option value="SM2">SM2 (非对称)</option>
                            <option value="RSA">RSA (非对称)</option>
                            <option value="SM4">SM4 (对称)</option>
                            <option value="AES">AES (对称)</option>
                        </select>
                    </div>
                    <div id="protectionKeySection" class="hidden">
                        <label for="protectionKey" class="block text-sm font-medium text-gray-700 mb-1">保护密钥</label>
                        <select id="protectionKey" name="protectionKey" class="input-field w-full px-4 py-2">
                            <option value="">请选择保护密钥</option>
                            <!-- 数据将通过JavaScript动态加载 -->
                        </select>
                    </div>
                    <div>
                        <label for="description" class="block text-sm font-medium text-gray-700 mb-1">描述</label>
                        <textarea id="description" name="description" class="input-field w-full px-4 py-2" rows="3"></textarea>
                    </div>
                </div>
                <div class="flex justify-end gap-3 mt-6">
                    <button type="button" onclick="closeModal('addKeyModal')" class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-all">
                        取消
                    </button>
                    <button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-all">
                        保存
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 密钥详情模态框 -->
    <div id="keyDetailModal" class="modal-overlay hidden">
        <div class="modal-content">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-xl font-semibold">密钥详情</h3>
                <button onclick="closeModal('keyDetailModal')" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            <div id="keyDetailContent">
                <!-- 数据将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>
    
    <script>
        // 初始化数据
        function initData() {
            try {
                // 显示加载状态

                // 初始化密钥数据
                if (!localStorage.getItem('keys')) {
                    const initialKeys = [
                        {
                            id: 'MK-001',
                            name: '应用主密钥1',
                            type: 'main',
                            algorithm: 'SM2',
                            protectionKey: null,
                            description: '系统默认应用主密钥',
                            createdAt: '2024-01-15 10:30:00',
                            status: 'active'
                        },
                        {
                            id: 'KEK-001',
                            name: '密钥加密密钥1',
                            type: 'kek',
                            algorithm: 'SM4',
                            protectionKey: null,
                            description: '用于加密DEK的密钥',
                            createdAt: '2024-01-15 11:00:00',
                            status: 'active'
                        },
                        {
                            id: 'DEK-001',
                            name: '数据加密密钥1',
                            type: 'dek',
                            algorithm: 'AES',
                            protectionKey: 'MK-001',
                            description: '用于加密业务数据的密钥',
                            createdAt: '2024-01-15 12:00:00',
                            status: 'active'
                        }
                    ];
                    localStorage.setItem('keys', JSON.stringify(initialKeys));
                }

                // 隐藏加载状态
                setTimeout(() => {
                    hideToast();
                }, 1000);
            } catch (error) {
                console.error('初始化数据失败:', error);
                showToast('初始化数据失败', 'error');
            }
        }
        
        // 加载密钥列表
        function loadKeys() {
            try {
                const keys = JSON.parse(localStorage.getItem('keys') || '[]');
                
                // 加载应用主密钥
                const mainKeys = keys.filter(key => key.type === 'main');
                loadKeysTable('mainKeysTable', mainKeys);
                
                // 加载KEK密钥
                const kekKeys = keys.filter(key => key.type === 'kek');
                loadKeysTable('kekKeysTable', kekKeys);
                
                // 加载DEK密钥
                const dekKeys = keys.filter(key => key.type === 'dek');
                loadDekKeysTable('dekKeysTable', dekKeys);
            } catch (error) {
                console.error('加载密钥列表失败:', error);
                showToast('加载密钥列表失败', 'error');
            }
        }
        
        // 加载普通密钥表格
        function loadKeysTable(tableId, keys) {
            const tableBody = document.getElementById(tableId);
            tableBody.innerHTML = '';
            
            if (keys.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center py-8 text-gray-500">
                            <i class="fas fa-key text-4xl mb-2 opacity-20"></i>
                            <p>暂无密钥数据</p>
                        </td>
                    </tr>
                `;
                return;
            }
            
            keys.forEach(key => {
                const row = document.createElement('tr');
                row.className = 'border-b border-[rgba(99,116,139,0.1)] hover:bg-[rgba(59,130,246,0.05)] transition-all';
                
                row.innerHTML = `
                    <td class="py-4 px-4">${key.id}</td>
                    <td class="py-4 px-4 font-medium">${key.name}</td>
                    <td class="py-4 px-4">
                        <span class="algorithm-badge algorithm-${key.algorithm.toLowerCase()}">${key.algorithm}</span>
                    </td>
                    <td class="py-4 px-4 text-gray-500">${key.createdAt}</td>
                    <td class="py-4 px-4">
                        <span class="status-badge status-${key.status}">${key.status === 'active' ? '活跃' : '禁用'}</span>
                    </td>
                    <td class="py-4 px-4">
                        <button onclick="viewKeyDetail('${key.id}')" class="text-blue-500 hover:text-blue-700 mr-3">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button onclick="toggleKeyStatus('${key.id}')" class="text-yellow-500 hover:text-yellow-700">
                            <i class="fas fa-toggle-${key.status === 'active' ? 'on' : 'off'}"></i>
                        </button>
                    </td>
                `;
                
                tableBody.appendChild(row);
            });
        }
        
        // 加载DEK密钥表格
        function loadDekKeysTable(tableId, keys) {
            const tableBody = document.getElementById(tableId);
            tableBody.innerHTML = '';
            
            if (keys.length === 0) {
                tableBody.innerHTML = `
                    <tr>
                        <td colspan="7" class="text-center py-8 text-gray-500">
                            <i class="fas fa-key text-4xl mb-2 opacity-20"></i>
                            <p>暂无DEK密钥数据</p>
                        </td>
                    </tr>
                `;
                return;
            }
            
            keys.forEach(key => {
                const row = document.createElement('tr');
                row.className = 'border-b border-[rgba(99,116,139,0.1)] hover:bg-[rgba(59,130,246,0.05)] transition-all';
                
                row.innerHTML = `
                    <td class="py-4 px-4">${key.id}</td>
                    <td class="py-4 px-4 font-medium">${key.name}</td>
                    <td class="py-4 px-4">
                        <span class="algorithm-badge algorithm-${key.algorithm.toLowerCase()}">${key.algorithm}</span>
                    </td>
                    <td class="py-4 px-4">${key.protectionKey}</td>
                    <td class="py-4 px-4 text-gray-500">${key.createdAt}</td>
                    <td class="py-4 px-4">
                        <span class="status-badge status-${key.status}">${key.status === 'active' ? '活跃' : '禁用'}</span>
                    </td>
                    <td class="py-4 px-4">
                        <button onclick="viewKeyDetail('${key.id}')" class="text-blue-500 hover:text-blue-700 mr-3">
                            <i class="fas fa-eye"></i>
                        </button>
                        <button onclick="toggleKeyStatus('${key.id}')" class="text-yellow-500 hover:text-yellow-700">
                            <i class="fas fa-toggle-${key.status === 'active' ? 'on' : 'off'}"></i>
                        </button>
                    </td>
                `;
                
                tableBody.appendChild(row);
            });
        }
        
        // 打开新建密钥模态框
        function openAddKeyModal(keyType) {
            const modal = document.getElementById('addKeyModal');
            const modalTitle = document.getElementById('modalTitle');
            const keyTypeInput = document.getElementById('keyType');
            const protectionKeySection = document.getElementById('protectionKeySection');
            const protectionKeySelect = document.getElementById('protectionKey');
            
            // 设置模态框标题
            const typeNames = {
                'main': '应用主密钥',
                'kek': 'KEK密钥',
                'dek': 'DEK密钥'
            };
            modalTitle.textContent = `新建${typeNames[keyType]}`;
            keyTypeInput.value = keyType;
            
            // 清空表单
            document.getElementById('addKeyForm').reset();
            
            // 显示/隐藏保护密钥选择
            if (keyType === 'dek') {
                protectionKeySection.classList.remove('hidden');
                // 加载保护密钥选项
                loadProtectionKeys();
            } else {
                protectionKeySection.classList.add('hidden');
            }
            
            // 使用淡入动画显示模态框
            modal.classList.remove('hidden');
            setTimeout(function() {
                modal.classList.add('modal-show');
            }, 10);
        }
        
        // 加载保护密钥选项
        function loadProtectionKeys() {
            const protectionKeySelect = document.getElementById('protectionKey');
            const keys = JSON.parse(localStorage.getItem('keys') || '[]');
            
            // 保护密钥可以是应用主密钥或KEK
            const protectionKeys = keys.filter(key => 
                key.type === 'main' || key.type === 'kek'
            );
            
            protectionKeySelect.innerHTML = '<option value="">请选择保护密钥</option>';
            
            protectionKeys.forEach(key => {
                const option = document.createElement('option');
                option.value = key.id;
                option.textContent = `${key.id} - ${key.name} (${key.type === 'main' ? '主密钥' : 'KEK'})`;
                protectionKeySelect.appendChild(option);
            });
        }
        
        // 关闭模态框
        function closeModal(modalId) {
            const modal = document.getElementById(modalId);
            // 使用淡出动画隐藏模态框
            modal.classList.remove('modal-show');
            setTimeout(function() {
                modal.classList.add('hidden');
            }, 300);
        }
        
        // 查看密钥详情
        function viewKeyDetail(keyId) {
            const keys = JSON.parse(localStorage.getItem('keys') || '[]');
            const key = keys.find(k => k.id === keyId);
            
            if (key) {
                const modal = document.getElementById('keyDetailModal');
                const content = document.getElementById('keyDetailContent');
                
                const typeNames = {
                    'main': '应用主密钥',
                    'kek': 'KEK密钥',
                    'dek': 'DEK密钥'
                };
                
                content.innerHTML = `
                    <div class="space-y-4">
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">密钥ID</label>
                                <div class="text-gray-800">${key.id}</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">密钥类型</label>
                                <span class="key-type-badge key-type-${key.type}">${typeNames[key.type]}</span>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">密钥名称</label>
                                <div class="text-gray-800">${key.name}</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">算法类型</label>
                                <span class="algorithm-badge algorithm-${key.algorithm.toLowerCase()}">${key.algorithm}</span>
                            </div>
                            ${key.type === 'dek' ? `
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">保护密钥</label>
                                <div class="text-gray-800">${key.protectionKey}</div>
                            </div>
                            ` : ''}
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">创建时间</label>
                                <div class="text-gray-800">${key.createdAt}</div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-600 mb-1">状态</label>
                                <span class="status-badge status-${key.status}">${key.status === 'active' ? '活跃' : '禁用'}</span>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-600 mb-1">描述</label>
                            <div class="text-gray-800 p-3 bg-gray-50 rounded-lg">
                                ${key.description || '无'}
                            </div>
                        </div>
                    </div>
                `;
                
                modal.classList.remove('hidden');
            }
        }
        
        // 切换密钥状态
        function toggleKeyStatus(keyId) {
            try {
                // 数据验证
                if (!keyId) {
                    showToast('参数错误', 'error');
                    return;
                }

                const keys = JSON.parse(localStorage.getItem('keys') || '[]');
                const keyIndex = keys.findIndex(key => key.id === keyId);
                
                if (keyIndex !== -1) {
                    keys[keyIndex].status = keys[keyIndex].status === 'active' ? 'inactive' : 'active';
                    localStorage.setItem('keys', JSON.stringify(keys));
                    loadKeys();
                    showToast('密钥状态已更新', 'success');
                } else {
                    showToast('密钥不存在', 'error');
                }
            } catch (error) {
                console.error('更新密钥状态失败:', error);
                showToast('更新密钥状态失败', 'error');
            }
        }
        
        // 添加密钥
        function addKey(keyData) {
            try {
                // 数据验证
                if (!keyData.keyName || !keyData.keyType || !keyData.algorithm) {
                    showToast('请填写必填字段', 'error');
                    return;
                }

                // 验证DEK必须选择保护密钥
                if (keyData.keyType === 'dek' && !keyData.protectionKey) {
                    showToast('DEK密钥必须选择保护密钥', 'error');
                    return;
                }

                const keys = JSON.parse(localStorage.getItem('keys') || '[]');
                
                // 生成密钥ID
                const typePrefixes = {
                    'main': 'MK',
                    'kek': 'KEK',
                    'dek': 'DEK'
                };
                const typeCount = keys.filter(k => k.type === keyData.keyType).length + 1;
                const keyId = `${typePrefixes[keyData.keyType]}-${String(typeCount).padStart(3, '0')}`;
                
                const newKey = {
                    id: keyId,
                    name: keyData.keyName,
                    type: keyData.keyType,
                    algorithm: keyData.algorithm,
                    protectionKey: keyData.protectionKey || null,
                    description: keyData.description || '',
                    createdAt: new Date().toISOString().slice(0, 19).replace('T', ' '),
                    status: 'active'
                };
                
                keys.push(newKey);
                localStorage.setItem('keys', JSON.stringify(keys));
                loadKeys();
                showToast('密钥创建成功', 'success');
                closeModal('addKeyModal');
            } catch (error) {
                console.error('添加密钥失败:', error);
                showToast('添加密钥失败', 'error');
            }
        }
        
        // 显示Toast消息
        function showToast(message, type = 'success') {
            const toastContainer = document.getElementById('toast-container');
            const toast = document.createElement('div');
            
            const typeClasses = {
                'success': 'bg-green-500 text-white',
                'error': 'bg-red-500 text-white',
                'warning': 'bg-yellow-500 text-white',
                'info': 'bg-blue-500 text-white'
            };
            
            toast.className = `px-4 py-2 rounded-lg shadow-lg mb-2 ${typeClasses[type]} transition-all duration-300 transform translate-x-full`;
            toast.innerHTML = `
                <div class="flex items-center">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} mr-2"></i>
                    <span>${message}</span>
                </div>
            `;
            
            toastContainer.appendChild(toast);
            
            // 动画效果
            setTimeout(() => {
                toast.classList.remove('translate-x-full');
            }, 10);
            
            // 自动关闭
            setTimeout(() => {
                toast.classList.add('opacity-0', 'translate-x-full');
                setTimeout(() => {
                    toast.remove();
                }, 300);
            }, 3000);
        }
        
        // 动态计算高度
        function calculateDynamicHeight() {
            try {
                const mainContent = document.getElementById('main-content');
                if (mainContent) {
                    const viewportHeight = window.innerHeight;
                    const offsetTop = mainContent.offsetTop;
                    mainContent.style.minHeight = (viewportHeight - offsetTop) + 'px';
                }
            } catch (error) {
                console.error('计算高度失败:', error);
            }
        }

        // 事件监听
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化数据
            initData();
            
            // 加载密钥列表
            loadKeys();
            
            // 计算动态高度
            calculateDynamicHeight();
            
            // 选项卡切换
            const tabBtns = document.querySelectorAll('.tab-btn');
            tabBtns.forEach(btn => {
                btn.addEventListener('click', function() {
                    // 移除所有激活状态
                    tabBtns.forEach(b => b.classList.remove('active'));
                    document.querySelectorAll('.tab-content').forEach(content => content.classList.add('hidden'));
                    
                    // 添加当前激活状态
                    this.classList.add('active');
                    const targetTab = this.getAttribute('data-tab');
                    document.getElementById(targetTab).classList.remove('hidden');
                });
            });
            
            // 表单提交
            const addKeyForm = document.getElementById('addKeyForm');
            addKeyForm.addEventListener('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData(this);
                const keyData = Object.fromEntries(formData);
                
                addKey(keyData);
            });
            
            // 点击模态框外部关闭
            window.addEventListener('click', function(e) {
                if (e.target.classList.contains('modal-overlay')) {
                    e.target.classList.add('hidden');
                }
            });
            
            // ESC键关闭模态框
            window.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    document.querySelectorAll('.modal-overlay').forEach(modal => {
                        modal.classList.add('hidden');
                    });
                }
            });
        });

        // 窗口大小变化时重新计算高度
        window.addEventListener('resize', function() {
            calculateDynamicHeight();
        });
    </script>
</body>
</html>